property ancestor
property pTarget,pContext

property pVarnames

property pRules

property e,t,f

on new me,a
  me.ancestor = script ("scrLambda").new(a)
  me.pRules = []
  return me
end

on TryGetVarNames me,varClosure
  if varClosure.ilk = #LingoF_LambdaExpression then
    v = varClosure.getUnboundedVars()
    repeat with vn in me.pVarNames
      v.deleteOne(vn)
    end repeat
    return v
  end if
  return []
end

on matchIf me , a1 , a2 , a3
  me.e = a1
  me.t = a2
  me.f = a3
  return me[#itdoesntmatter]
end

on | me , cond,expr
  if not count(me.pRules) then me.length = me.length-1
  me.pRules.add([#condition: cond , #expression: expr])
  return me
end

on ex me,x,plist
  vnames = me.ancestor.TryGetVarNames(x)
  if not (vnames.count()) then return x
  return x.EvalWith(plist)
end

on ApplyList me,params
  
  body = params[1]
  
  a = (count(me.pRules)=0)
  
  plist = [:]
  repeat with i = 1 to params.count()-a
    plist.addProp(params[i+a],pVarNames[i])
  end repeat
  
  repeat with rule in me.pRules
    r = me.ex(rule.condition,plist)
    if r then return me.ex(rule.expression,plist)
  end repeat  
  
  return me.ex(body,plist)
end 